﻿using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EasyMirai
{
    public partial class MainForm : Form
    {
        private Process mirai;
        private ProcessStartInfo info = new ProcessStartInfo()
        {
            FileName = "java.exe",
            Arguments = "-cp ./* net.mamoe.mirai.console.pure.MiraiConsolePureLoader",
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardInput = true,
            RedirectStandardError = true,
            StandardOutputEncoding = Encoding.ASCII,
            StandardErrorEncoding = Encoding.ASCII,
            WorkingDirectory = Environment.CurrentDirectory
        };
        private bool Downloading;
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            button2_Click(sender, e);
            if (!File.Exists("login.txt"))
            {
                Login login = new Login();
                if(login.ShowDialog() != DialogResult.OK)
                {
                    Close();
                }
            }
            mirai = Process.Start(info);
            mirai.BeginOutputReadLine();
            mirai.BeginErrorReadLine();
            mirai.OutputDataReceived += Mirai_OutputDataReceived;
            mirai.ErrorDataReceived += Mirai_ErrorDataReceived;
            try
            {
                RegistryKey subKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment");
                string currentVerion = subKey.GetValue("CurrentVersion").ToString();
                AddLog("Detected java version: " + currentVerion,Color.Lime);
                if(Convert.ToDecimal(currentVerion) < (decimal)1.8) 
                {
                    AddLog("Java version is too low!");
                    throw new Exception();
                }
            }
            catch
            {
                AddLog("请到这里下载并且安装Java后继续");
                var p = Process.Start("https://java.com/en/download/");
                p.WaitForExit();
                Process.Start(Application.ExecutablePath);
                Application.Exit();
            }

        }

        private void Mirai_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            try
            {
                if(e.Data == null)
                {
                    return;
                }
                if (e.Data.ToLower().Contains("create a system terminal") || e.Data.Contains("?"))
                {
                    return;
                }
                AddLog(e.Data, Color.Red);
            }
            catch
            {

            }

        }

        private void Mirai_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            try
            {
                if(e.Data == null){
                    return;
                }
                var bytes = Encoding.ASCII.GetBytes(e.Data);
                AddLog(Encoding.UTF8.GetString(bytes), Color.Yellow);
                if (e.Data.Contains("mirai-console started successfully"))
                {
                    var cmd = File.ReadAllText("login.txt", Encoding.UTF8);
                    mirai.StandardInput.WriteLine(cmd.Trim());
                }
            }
            catch
            {

            }

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.ScrollToCaret();
        }

        private void AddLog(string log, Color color = default)
        {
            if(log == null)
            {
                return;
            }
            //奇葩字眼移除
            log = log.Replace("[m", "").Replace("[0m","").Replace("[92m","").Replace("","");
            try
            {
                if (color != default)
                {
                    richTextBox1.SelectionStart = richTextBox1.TextLength;
                    richTextBox1.SelectionLength = 0;
                    richTextBox1.SelectionColor = color;
                }
                richTextBox1.AppendText(log + Environment.NewLine);
                richTextBox1.SelectionColor = richTextBox1.ForeColor;
            }
            catch
            {
                richTextBox1.Invoke((MethodInvoker)delegate
                {
                    if (color != default)
                    {
                        richTextBox1.SelectionStart = richTextBox1.TextLength;
                        richTextBox1.SelectionLength = 0;
                        richTextBox1.SelectionColor = color;
                    }
                    richTextBox1.AppendText(log + Environment.NewLine);
                    richTextBox1.SelectionColor = richTextBox1.ForeColor;
                });
            }


        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                mirai.Kill();
            }
            catch
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AddLog("正在重启Mirai", Color.White);
            if(mirai != null)
            {
                if (!mirai.HasExited)
                    mirai.Kill();
            }

            mirai = Process.Start(info);
            mirai.BeginOutputReadLine();
            mirai.BeginErrorReadLine();
            mirai.OutputDataReceived += Mirai_OutputDataReceived;
            mirai.ErrorDataReceived += Mirai_ErrorDataReceived;
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            if (Downloading)
            {
                AddLog("已经存在正在下载的更新！稍安勿躁！",Color.Yellow);
                return;
            }
            if (File.Exists("data\\MiraiNative\\CQP.dll"))
            {
                File.Delete("data\\MiraiNative\\CQP.dll");
            }
            Downloading = true;
            if (mirai != null)
            {
                if (!mirai.HasExited)
                    mirai.Kill();
            }
            using (MiraiFiles fileCheck = new MiraiFiles(richTextBox1))
            {
                if (!fileCheck.FileCheck())
                {
                    AddLog("正在更新...", Color.Cyan);
                    fileCheck.DownloadFiles();
                    do
                    {
                        await Task.Delay(1000);
                    } while (fileCheck.Downloading);
                }
                else
                {
                    AddLog("恭喜你！当前使用的Mirai是最新版本！.", Color.Lime);
                }
            }
            Downloading = false;
            mirai = Process.Start(info);
            mirai.BeginOutputReadLine();
            mirai.BeginErrorReadLine();
            mirai.OutputDataReceived += Mirai_OutputDataReceived;
            mirai.ErrorDataReceived += Mirai_ErrorDataReceived;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (mirai != null)
            {
                if (!mirai.HasExited)
                    mirai.Kill();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (mirai != null)
            {
                if (!mirai.HasExited)
                    mirai.Kill();
            }
            mirai = Process.Start(info);
            mirai.BeginOutputReadLine();
            mirai.BeginErrorReadLine();
            mirai.OutputDataReceived += Mirai_OutputDataReceived;
            mirai.ErrorDataReceived += Mirai_ErrorDataReceived;
        }
    }
}
